<?php

declare (strict_types = 1);

namespace app\store\service\user;

use app\common\library\helper;
use app\common\service\BaseService;
use app\store\model\BoxCollect as BoxCollectModel;
use app\store\model\PickUp;
use app\store\model\UserAddress;
use think\facade\Db;
use think\facade\Log;


/**
 * 盒柜
 * Class Goods
 * @package app\store\service
 */
class Collect extends BaseService
{
    /**
     * @param $params
     * @return array
     */
   public function getIndex($params):array
   {
       $condition = [];
       //不算寄售记录
       $condition[] = ['entrust_status', '=', 0];
       if (isset($params['goods_name']) && $params['goods_name']) {
           $condition[] = ['goods_name', 'like', "%{$params['goods_name']}%"];
       }
       if (isset($params['status']) && $params['status'] != 'all') {
           $condition[] = ['status', '=', $params['status']];
       }
       if (isset($params['delivery_status']) && $params['delivery_status']) {
           $condition[] = ['delivery_status', '=', $params['delivery_status']];
       }
       if (isset($params['id']) && $params['id']) {
           $condition[] = ['goods_name', 'like', "%{$params['goods_name']}%"];
       }

       if(isset($params['is_passed_thirty_unpicked'])){
           if($params['is_passed_thirty_unpicked'] == 1){
               //超过30天未提货
               $condition[] = ['status', '=', 0];
               $condition[] = ['toy_box_collect.created_at', '<', date('Y-m-d H:i:s',time() - 30 * 86400)];
           }
       }

       $tmp_condition = [
           ['created_at', '<', date('Y-m-d H:i:s',time() - 30 * 86400)],
           ['status', '=', 0],
       ];
       $passed_thirty_unpicked_num = BoxCollectModel::where($tmp_condition)->count();

       $userCond = [];
       if(isset($params['search']) && $params['search']){
           $userCond[] = ['nick_name|mobile|User.user_id', 'like', "%{$params['search']}%"];
       }

       $list = BoxCollectModel::with(['user.avatar' => function ($query) {
           $query->withField(['nick_name', 'user_id','mobile','avatar_id']);
       }, 'image'])
           ->hasWhere('user', $userCond)
           ->where($condition)
           ->order('collect_id', 'DESC')
           //->select()
           ->paginate($params['limit'] ?? 15)
           ->each(function (&$item){
               //未发货显示是否超30天
               $item['passed_thirty_unpicked'] = 0;
               if($item['status'] == 0){
                   if(time() - strtotime($item['created_at']) > 30 * 86400){
                       $item['passed_thirty_unpicked'] = 1;
                   }
               }
               $item['user']['address'] = !empty($this->getUserDefaultAddress($item['user_id'])) ?$this->getUserDefaultAddress($item['user_id']) : new \stdClass();
           })
           ->toArray();
       return [
           'passed_thirty_unpicked_num' => $passed_thirty_unpicked_num,
           'list' => $list
       ];
   }

    /**获取默认收货地址
     * @param $user_id
     * @return array
     */
   public function getUserDefaultAddress($user_id):array
   {
       //显示默认地址
       $condition = [
           'user_id' => $user_id,
           'is_default' => 1,
           'is_delete' => 0
       ];
       $address = UserAddress::where($condition)->find();
       if(!$address){
           return [];
       }
       $address->pcr_address = helper::jsonDecode($address->pcr_address);
       return $address->toArray();
   }

    /**提货-支持批量
     * @param $collect_ids
     * @return bool
     */
   public function getPickUp($collect_ids):bool
   {
       $box_collect = BoxCollectModel::with(['user' => function ($query) {
           $query->withField(['nick_name', 'user_id','mobile']);
       }])->whereIn('collect_id',$collect_ids)
           ->select()
           ->each(function (&$item){
               $item['address'] = $this->getUserDefaultAddress($item['user_id']);
           })
           ->toArray();
       foreach ($box_collect as $iitem){
           if($iitem['status'] != 0){
               throwError('盒柜ID：【'.$iitem['collect_id'].'】已被提货');
           }
           if(empty($iitem['address'])){
               throwError("用户{$iitem['user']['nick_name']}地址为空");
           }
       }
       //根据用户id合并
       $tmp1 = $tmp2 = [];
       foreach ($box_collect as $ival){
           $tmp1[$ival['user_id']][] = $ival;
       }

       foreach ($tmp1 as $val){
           $tmp2[] = [
               'collect_id' => array_column($val,'collect_id'),
               'user_id' => $val[0]['user_id'],
               'address' => $val[0]['address'],
               'user' => $val[0]['user']
           ];
       }
       //批量处理提货
       foreach ($tmp2 as $datum){
           $flag = $this->getPickUpFunc($datum);
           if(!$flag){
               throwError("用户【{$datum['user']['nick_name']}】提货失败");
           }
       }
       return true;
   }


    /**提货
     * @param $data
     * @return bool
     */
   public function getPickUpFunc($data): bool
   {
       Db::startTrans();
       try {
           $order_no = orderNo();
           //创建提货记录
           $res = PickUp::create([
               'user_id'     => $data['user_id'],
               'pick_no'     => $order_no,
               'name'        => $data['address']['name'] ,
               'phone'       => $data['address']['phone'],
               'pcr_address' => $data['address']['pcr_address'],
               'detail'      => $data['address']['detail'],
               'is_free_shipping' => 1, //包邮
           ]);
           if (!$res) {
               throw new \Exception("提货失败");
           }
           // 更新提货商品
           BoxCollectModel::update([
               'status'     => 1,
               'pick_up_id' => $res->id,
           ], [['collect_id', 'IN', $data['collect_id']]]);
           Db::commit();
           return true;
       }catch (\Exception $e){
           Log::info($e->getMessage());
           return false;
       }
   }



}
